import Vue from 'vue'
import {Message} from 'element-ui';
import VueResource from 'vue-resource'
import Cookie from './js.cookie.js'
import router from '../router'
import utils from './utils.js'
import * as consts from './CONST.js'

Vue.use(VueResource)
Vue.http.options.credentials = true
Vue.http.options.emulateJSON = true
Vue.http.options.xhr = {withCredentials: true}
Vue.http.options.headers = {
}

const devlopment = process.env.NODE_ENV == 'development'

function showToast(msg, fn) {
    fn && fn()
    msg && Message({
        message: msg,
        type: 'error'
    });
}

function goIndex() {
    if (navigator.userAgent.toLowerCase().match(/fangxin/i)) {
    } else {
        router.push({name: 'Index'});
    }
}

function refreshPage() {
    if (navigator.userAgent.toLowerCase().match(/fangxin/i)) {
    } else {
        // router.go(0)
        window.location.reload();
    }
}

/**
 * 将url替换为模拟数据url
 * @param url api.js中的url
 * @returns {*}
 */
function handlerImitatorUrl(url) {
    let prefixs = process.env.API_DOMAIN

    for (let pre of Object.values(prefixs)) {
        if (url.startsWith(pre)) {
            url = url.replace(pre, '')
        }
    }
    return consts.imiator_prefix + url;
}

/**
 *
 * @param url 请求地址
 * @param method 提交方法
 * @param data 传递的参数
 * @param applicationJSON 是否要用application/json形式传递数据
 * @private
 */
function _http(url, method, data, applicationJSON = false) {
    // imitator用
    if (method == 'ijsonp') {
        data.jsonp_param_name = 'callback';
    }
    if ((method == 'ijsonp' || method == 'ipost')) {
        if (devlopment && !consts.ignore_imtator) {
            url = handlerImitatorUrl(url)
        }
        method = method.substr(1) // 非开发环境，直接替换
    }

    let http_promise = null;

    if (method == 'post') {
        let post_body = data;
        let post_options = {};

        if (applicationJSON) {
            post_options.emulateJSON = false;
            post_options.headers = {
                'Content-Type': 'application/json; charset=UTF-8'
            }
        }
        http_promise = Vue.http[method](url, post_body, post_options)
    } else if (method == "jsonp") {
        let jsonp_options = {
            params: data // vue-resource 需要的处理
        }
        http_promise = Vue.http[method](url, jsonp_options)
    } else {
        http_promise = Vue.http[method](url, data)
    }

    return http_promise.then((response) => {
        // console.debug('http-response===', response)
        if (response.data.trans_result) {
          return response.data.trans_result
        } else {
          if (Number(response.data.status.status_code) == 0) {
              return response.data.result;
          } else {
              let msg = response.data.status.status_reason
              let fn = ''
              switch (Number(response.data.status.status_code)) {
                  case '120':
                      if (!devlopment) {
                          fn = utils.doLoginOut
                      }
                      break
                  // case '60000': // 投票已结束
                  // case '60001': // 选项不存在
                  // case '60002': // 最多选X项
                  // case '60003': // 您已参与过该投票
                  //     fn = refreshPage
                  //     break
                  default:
                      fn = ''
              }
              response.data.status._callback = setTimeout(function () {
                  showToast(msg, fn)
              }, 50);
              return {_error: response.data.status};
          }
        }
    }, (response) => {
        // Vue.$loading(false);
        Message({
            message: '网络异常，请刷新后重试',
            type: 'error'
        });
        if (window.watcher) {
            watcher.ajaxErr({
                url: url,
                req: data,
                rep: response
            })
        }
    })
}

Vue.$_http = Vue.prototype.$_http = _http

export default _http
